'use strict';

const formidable = require("formidable");
const path = require('path');
const fs = require('fs');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const dayjs = require('dayjs');
const Controller = require('egg').Controller;

class UploadController extends Controller {
  async parse(req) {
    const form = new formidable.IncomingForm();
    return new Promise((resolve, reject) => {
      form.parse(req, (err, fields, files) => {
        resolve({ fields, files })
      })
    });
  }

  // 上传图片
  async image() {
    let { ctx } = this;
    const extraParams = await this.parse(ctx.req);
    if(!extraParams.fields||!extraParams.fields.type){
      return ctx.helper.resError('type不能为空');
    }
    if(!extraParams.files||!extraParams.files.file){
      return ctx.helper.resError('图片不能为空');
    }
    let type = extraParams.fields.type;
    let file = extraParams.files.file;
    if(file.type!='image/png'&&file.type!='image/jpeg'){
      return ctx.helper.resError('上传图片格式不对');
    }
    if(file.size>(10 * 1024 * 1024)){
      return ctx.helper.resError('图片太大不要超过10M');
    }
    let stream = fs.createReadStream(file.path);
    // 基础的目录
    let uplaodBasePath = 'app/public/upload/image';
    // 生成文件名
    let filename = `${Date.now()}${Number.parseInt(
      Math.random() * 1000,
    )}${path.extname(file.name).toLocaleLowerCase()}`;
    // 生成文件夹
    let dirname = `${type}/${dayjs(Date.now()).format('YYYY/MM/DD')}`;
    function mkdirsSync(dirname) {
      if (fs.existsSync(dirname)) {
        return true;
      } else {
        if (mkdirsSync(path.dirname(dirname))) {
          fs.mkdirSync(dirname);
          return true;
        }
      }
    }
    mkdirsSync(path.join(uplaodBasePath, dirname));
    // 生成写入路径
    let target = path.join(uplaodBasePath, dirname, filename);
    // 写入流
    let writeStream = fs.createWriteStream(target);
    try {
      //异步把文件流 写入
      await awaitWriteStream(stream.pipe(writeStream));
      return ctx.helper.resSuccess(`/public/upload/image/${dirname}/${filename}`);
    } catch (err) {
      //如果出现错误，关闭管道
      await sendToWormhole(stream);
      return ctx.helper.resError('上传失败');
    }
  }
}

module.exports = UploadController;
